package com.nanchen.compressimage;

import com.nanchen.compresshelper.CompressHelper;
import com.nanchen.compresshelper.FileUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Random;


import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;

import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import ohos.utils.net.Uri;


public class MainAbility extends Ability {
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 11;
    private Image mImageOld;
    private Image mImageNew;
    private ImageSource imageSource;
    public static final int PICK_IMAGE_REQUEST = 1;
    public static final int RESULT_OK = -1;
    private Text mTextOld;
    private Text mTextNew;
    private File oldFile;
    private File newFile;


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_main);

        initInstances();
        Button button = (Button) findComponentById(ResourceTable.Id_button);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED) {
                    // 应用未被授予权限
                    if (canRequestPermission("ohos.permission.READ_USER_STORAGE")) {
                        // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                        requestPermissionsFromUser(
                                new String[]{"ohos.permission.READ_USER_STORAGE", "ohos.permission.READ_MEDIA"}, MY_PERMISSIONS_REQUEST_CAMERA);
                    }
                } else {
                    // 显示应用需要权限的理由，提示用户进入设置授权
                    Intent secondIntent = new Intent();
                    // 指定待启动FA的bundleName和abilityName
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(MainAbility.this.getBundleName())
                            .withAbilityName(ImageListAbility.class.getName())
                            .build();
                    secondIntent.setOperation(operation);
                    // 通过AbilitySlice的startAbility接口实现启动另一个页面
                    startAbilityForResult(secondIntent, PICK_IMAGE_REQUEST);
                }

            }
        });
        Button button1 = (Button) findComponentById(ResourceTable.Id_button1);
        button1.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                compress();
            }
        });

    }


    private void initInstances() {
        mImageOld = (Image) findComponentById(ResourceTable.Id_main_image_old);
        mImageNew = (Image) findComponentById(ResourceTable.Id_main_image_new);
        mTextOld = (Text) findComponentById(ResourceTable.Id_main_text_old);
        mTextNew = (Text) findComponentById(ResourceTable.Id_main_text_new);
        clearImage();
    }

    public void compress() {
        // 默认的压缩方法，多张图片只需要直接加入循环即可
        if (oldFile == null) {
            return;
        }
        newFile = CompressHelper.getDefault(getApplicationContext()).compressToFile(oldFile);
//        String yourFileName = "123.jpg";
//
//        // 你也可以自定义压缩
//        newFile = new CompressHelper.Builder(this)
//                .setMaxWidth(720)  // 默认最大宽度为720
//                .setMaxHeight(960) // 默认最大高度为960
//                .setQuality(80)    // 默认压缩质量为80
//                .setCompressFormat(CompressFormat.JPEG) // 设置默认压缩为jpg格式
//                .setFileName(yourFileName) // 设置你的文件名
//                .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
//                        Environment.DIRECTORY_PICTURES).getAbsolutePath())
//                .build()
//                .compressToFile(oldFile);

        ImageSource.DecodingOptions options = new ImageSource.DecodingOptions();
        ImageSource imageSource = null;
        try {
            imageSource = ImageSource.create(newFile.getCanonicalPath(), null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PixelMap pixelMap = imageSource.createPixelmap(options);
        mImageNew.setPixelMap(pixelMap);

        mTextNew.setText(String.format("Size : %s", getReadableFileSize(newFile.length())));
    }

    /* public void takePhoto(Component view) {
         Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
         intent.setType("image/*");
        // startActivityForResult(intent, PICK_IMAGE_REQUEST);
         startAbilityForResult(intent,PICK_IMAGE_REQUEST);
     }*/


    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent data) {
        super.onAbilityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
            if (data == null) {
                showError("Failed to open picture!");
                return;
            }
            String str = data.getStringParam("uri");
            if (str == null) {
                return;
            }
            Uri uri = Uri.parse(str);

            try {
                oldFile = FileUtil.getTempFile(this, uri);
                ImageSource.DecodingOptions options = new ImageSource.DecodingOptions();
                ImageSource imageSource = ImageSource.create(oldFile.getCanonicalPath(), null);
                PixelMap pixelMap = imageSource.createPixelmap(options);
                mImageOld.setPixelMap(pixelMap);
                mTextOld.setText(String.format("Size : %s", getReadableFileSize(oldFile.length())));
            } catch (IOException e) {
                showError("Failed to read picture data!");
                e.printStackTrace();
            }
        }
    }

    private ToastDialog toastDialog;

    public void showError(String errorMessage) {
        toastDialog.setText(errorMessage).show();
    }

    private int getRandomColor() {
        Random rand = new Random();
        return Color.argb(100, rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
    }


    private void clearImage() {
        mImageOld.setPixelMap(getRandomColor());
        mImageNew.setImageElement(null);
        mImageNew.setPixelMap(getRandomColor());
        mTextNew.setText("Size : -");
    }


    public String getReadableFileSize(long size) {
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}
